// index.js
var app = getApp();
var mta = require('../../common/mta_analysis.js');
var CryptoJS = require('../../common/tripledes.js');

//DES解密
function decryptByDES(ciphertext, key) {
  const keyHex = CryptoJS.enc.Utf8.parse(key);
  // direct decrypt ciphertext
  const decrypted = CryptoJS.DES.decrypt(ciphertext, keyHex, {
    iv: keyHex,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

Page({

  data: {
    // 判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    indicatorDots: false,
    autoplay: true,
    interval: 8000,
    duration: 1000,
    isAgree: true,
    stationname: "",
    target: "",
    globalcode: "",
    summary: [{
        name: '定制客运',
        url: '/customline/pages/index/index',
        icon: '/pages/image/custome.png',
        isenable: false,
        index: 0
      },
      {
        name: '城际拼车',
        url: '/rent/pages/index/index',
        icon: '/pages/image/rentoff.png',
        isenable: false,
        index: 1
      },
      {
        name: '旅游门票',
        url: '/Tourism/index/index',
        icon: '/pages/image/playoff.png',
        isenable: true,
        index: 2
      },
      {
        name: '机场接送',
        url: '/customline/pages/index/index',
        icon: '/pages/image/trainoff.png',
        isenable: false,
        index: 3
      }
    ],
    text: '',
    windowwidth: '',
    quxiao: false,
    animationData: "",
    // webHtmlData: {}
    // text: "由于微信小程序中无法获取到对应元素的宽度，这个时间只能写死或者根据text的长度估算出一个值。"
  },


  /**
   * 生命周期函数--监听页面加载
   */
  networking: function (u) {
    function setDate() {
      return wx.setStorage({
        key: 'disTime',
        data: app.disDate()
      })
    }
    // 轮播图
    var imgUrl = [
      `https://img.hn96606.com/images/banner1.jpg?${app.dates()}`,
      `https://img.hn96606.com/images/banner2.png?${app.dates()}`
    ];
    let that = this;
    wx.request({
      url: `https://img.hn96606.com/images/networkData.json?${app.dates()}`,
      headers: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        app.webHtmlData = res.data.webList;
        that.webHtmlData = res.data.webList;
        that.disCode = res.data.offLine;
        that.dis = res.data.wuyiDis;
        // 疫情下包车业务二维码
        that.yiqingCode = res.data.yiqingCode;
<<<<<<< HEAD
        // let dis = res.data.wuyiDis;
        let dis = false;
=======
        let dis = res.data.wuyiDis;
        // let dis = true;
>>>>>>> 4a311ec1eb844bd0fc0cc6d510f1f182f78f9439
        that.setData({
          disShow: dis,
          // 疫情提示弹出框
          yiqingShow: res.data.yiqingShow,
          yiqingUserCode: res.data.yiqingUserCode,
          yiqingDrCode: res.data.yiqingDrCode
        });
        app.discountShow = dis;

        // ===================================================
        // 更新版本
        // var url = decodeURIComponent(u.q);
        // wx.getStorage({
        //   key: 'disTime',
        //   success: function(res) {
        //     if (res.data.offLine == true && url.indexOf("l=push") >= 0 && url.indexOf("p=") >= 0 && url.indexOf("globalcode=") >= 0 && res.data !== app.disDate()) {
        //       that.setData({
        //         disImg: 'codeImg',
        //         disPromptImg: true
        //       })
        //       setDate();
        //     }
        //   },
        //   fail(err) {

        //   }
        // })

        // ===================================================
        // 判断车站扫码进入小程序
        var url = decodeURIComponent(u.q);
        if (res.data.offLine == true && url.indexOf("l=push") >= 0 && url.indexOf("p=") >= 0 && url.indexOf("globalcode=") >= 0) {
          wx.getStorage({
            key: 'disTime',
            success: function (res) {
              if (res.data !== app.disDate()) {
                that.setData({
                  disImg: 'codeImg',
                  disPromptImg: true
                })
                setDate();
              }
            },
            fail(err) {
              that.setData({
                disImg: 'codeImg',
                disPromptImg: true
              })
              setDate();
            }
          })
        }
        if (dis == true) {
          // 如果活动开启，添加一张活动轮播图
          imgUrl.unshift(`https://img.hn96606.com/images/bannerDis.png?${app.dates()}`);
          that.setData({
            disImg: 'disPImg',
            imgUrls: imgUrl
          })
        } else {
          that.setData({
            imgUrls: imgUrl
          })
        }
        // 实现每天弹出一次2020活动简介弹出框
        if (res.data.tongGao == true) {
          wx.getStorage({
            key: 'disTime',
            success: function (res) {
              if (res.data !== app.disDate()) {
                that.setData({
                  disImg: 'disPImg',
                  disPromptImg: true
                })
                setDate();
              }
            },
            fail(err) {
              that.setData({
                disImg: 'disPImg',
                disPromptImg: true
              })
              setDate();
            }
          })
        }

      }
    })
  },


  onLoad: function (options) {
    var url = decodeURIComponent(options.q);
    this.op = options;
    if (url.indexOf("type=register") >= 0) {
      var urltmp = '/pages/userMessage/userMessage?' + url.split("?")[1];
      wx.navigateTo({
        url: urltmp,
      });
    };
    // 为精确获取2020活动控制器（dis）,在app.js中获取有小概率未能及时获取到
    this.networking(options);
    // 车站扫码进入
    this.selectStation(options);

    try {
      // this.setData({
      //   imgUrls: app.appimg,
      // })


      // ==============结束================
      mta.Page.init();
      this.getActivity();
      this.getSystemConfig();
      this.data.windowwidth = wx.getSystemInfoSync().windowWidth;

    } catch (e) {
      console.log(e)
    }
  },
  // 调用微信用户信息接口
  userLogin: function () {
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.codes = res.code;
        }
      },
      fail: function () {}
    })
  },
  // 获取Token，如果用户授权，直接调用微信官方WX.getUserInfo方法获取用户信息，而不是弹框授权
  GetUserToken: function () {
    var that = this;
    // 通过 wx.getSetting 先查询一下用户是否授权了 "scope.record"
    try {
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            wx.login({
              success: function (res) {
                if (res.code) {
                  // 用户首次进入小程序时，如果检测到用户已经授权，则获取新的Token
                  wx.getUserInfo({
                    success(data) {
                      app.userinfo.nickname = data.userInfo.nickName ? data.userInfo.nickName : '';
                      app.userinfo.headimg = data.userInfo.avatarUrl;
                      that.putUserData(res.code, data.iv, data.encryptedData);
                      that.setData({
                        ModalSwitch: false
                      })
                    }
                  });
                }
              },
              fail: function (err) {}
            })
          } else {
            // 未授权的解决方案 ====  调用微信获取用户信息按钮
            that.userLogin();
            app.hideLoadings();
            that.setData({
              // 页面模态框开关
              // JS模态框开关
              ModalSwitch: true,
            })
          }
        },
        complete: () => {
          app.hideLoadings();
        }
      })
    } catch (err) {}
  },

  // 授权失败模态提示框
  shouquanFail: function () {
    wx.showModal({
      title: '授权失败',
      content: '服务器繁忙，请点击页面按钮重试',
      showCancel: false,
      success: function () {
        app.hideLoadings();
      }
    })
  },

  // 发送用户数据给后台
  putUserData: function (code, IV, EncryptedData) {
    app.hideLoadings();
    let that = this;
    // Token数据请求
    wx.request({
      url: app.serviceurl + 'GetToken',
      method: "POST",
      data: {
        code: code,
        options: JSON.stringify(app.o),
        IV: IV,
        EncryptedData: EncryptedData
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.AccessToken) {
          that.setData({
            ModalSwitch: false
          })
          let resData = res.data;
          if (resData.openId !== "") {
            app.optionsToken = resData.openId;
          }
          app.HandsetNumber = resData.HandsetNumber;
          app.IsRegister = resData.IsRegister;
          app.newUser = resData.IsNewUser;
          app.accesstoken = resData.AccessToken;
          // 是否为新用户
          app.IsFresh = resData.IsFresh;
          try {
            // 将用户数据存储进本地缓存
            wx.setStorage({
              key: '_userToken',
              data: {
                HandsetNumber: resData.HandsetNumber,
                IsRegister: resData.IsRegister,
                accesstoken: resData.AccessToken,
                userDate: new Date()
              },
            });
            // 疫情包车业务二维码页面
            if (that.yiqingCode && that.touser) {
              that.toUserList();
            }
            that.checkfrom(that.op)
          } catch (err) {}
        } else {
          that.shouquanFail();
        }
      },
      fail: function () {
        try {
          that.shouquanFail();
          app.hideLoadings();
        } catch (e) {}
      },
      complete: () => {
        app.hideLoadings();
      }
    })
  },
  prompt: function () {
    this.touser = true;
  },
  // 用户信息登记 == 疫情
  toUserMessage: function () {
    wx.scanCode({
      success: (res) => {
        let reportId = decryptByDES(res.result, 'lwspsystem').split(",")[0];
        wx.navigateTo({
          url: '/pages/userMessage/userMessage?reportId=' + reportId,
        })
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
  // 2020春节优惠活动隐藏活动提示
  disCancel() {
    this.setData({
      disPromptImg: false,
      yiqingShow: false
    })
  },
  disMessage() {
    this.setData({
      disPromptImg: false
    });
    if (this.disCode == true && this.dis == false) {
      wx.navigateTo({
        url: '/pages/discountsList/discountsList',
      })
    } else {
      wx.navigateTo({
        url: '/pages/discountMsg/discountMsg',
      })
    }
  },
  // 用户信息授权按钮  
  bindGetUserInfo(e) {
    try {
      let that = this;
      var user = e.detail;
      app.userinfo.nickname = user.userInfo.nickName ? user.userInfo.nickName : '';
      app.userinfo.headimg = user.userInfo.avatarUrl;
      that.putUserData(this.codes, user.iv, user.encryptedData);
    } catch (err) {}
  },

  selectStation: function (op) {
    //console.log(op.q)
    // 测试
    //let aa = 'https://m.hn96606.com/index.html?l=push&p=13193560707&globalcode=410901';
    // this.op = "";
    try {
      if (op.q) {
        var url = decodeURIComponent(op.q);
        if (url.indexOf("globalcode=") >= 0) {
          let UrlCode = url.split("globalcode=")[1];
          let that = this;
          let code = url.split("globalcode=")[1];
          let codeIndex = code.toString().substring(0, 4)
          wx.request({
            url: app.serviceurl + 'StationLine/QueryStations',
            success: function (res) {
              if (res.data.CityList == null || typeof (res.data.CityList) == 'undefined') {
                return;
              }
              let list = res.data.CityList;
              list.forEach((item, i) => {
                if (item.CityCode == codeIndex) {
                  item.StationList.forEach((val, index) => {
                    if (val.GlobalCode == code) {
                      that.setData({
                        stationname: val.StationName
                      })
                      app.stationName = val.StationName;
                      app.globalcode = val.GlobalCode;
                      wx.setStorage({
                        key: 'stationname',
                        data: val.StationName,
                      });
                      wx.setStorage({
                        key: 'globalcode',
                        data: val.GlobalCode,
                      });
                    }
                  })
                }
              })
            },
            fail: function (xhr) {

            },
            complete: function () {

            }
          })

        }
      }
    } catch (err) {

    }


  },
  // 跳转到乘客二维码页面 ============= 2020疫情措施
  toUserList: function () {
    wx.navigateTo({
      url: '/pages/yiqingCode/yiqingCode',
    })
  },
  urlToObject: function (url) {
    var urlObject = {};
    if (/\?/.test(url)) {
      var urlString = url.substring(url.indexOf("?") + 1);
      var urlArray = urlString.split("&");
      for (var i = 0, len = urlArray.length; i < len; i++) {
        var urlItem = urlArray[i];
        var item = urlItem.split("=");
        urlObject[item[0]] = item[1];
      }
      return urlObject;
    }
  },
  checkfrom: function (op) {
    try {
      this.op = "";
      if (op.q) {
        // 推广进入
        var url = decodeURIComponent(op.q);
        // 扫码进入首页默认起始车站
        if (url.indexOf("type=setstation") >= 0) {
          // this.urlToObject  URL转对象函数
          let objData = this.urlToObject(url)
          app.globalcode = objData.globalcode;
          app.stationName = objData.name;

          wx.setStorage({
            key: 'stationname',
            data: objData.name,
          });
          wx.setStorage({
            key: 'globalcode',
            data: objData.globalcode,
          });
          // wx.removeStorage({
          //   key: 'target',
          // })
          this.upload()

        }
        if (url.indexOf("yzx=zzxuanchuan") >= 0) {
          var urltmp = '/pages/xuanchuan/xuanchuan?' + url.split("?")[1];
          wx.navigateTo({
            url: urltmp,
          });
        }
        if (url.indexOf("l=push") >= 0) {
          let Topenid = url.split("=")[2];
          app.optionsP = Topenid;
          wx.setStorage({
            key: '_topenid',
            data: Topenid,
          })
        }
        // 
        if (url.indexOf("type=qcp") >= 0) {
          var urltmp = '/pages/buslines/buslines?' + url.split("?")[1];
          wx.navigateTo({
            url: urltmp,
          });
        } else if (url.indexOf("type=dzky") >= 0) {
          var urltmp = '';
          if (url.indexOf("scancode=") >= 0) {
            urltmp = '/customline/pages/linepre/linepre?' + url.split("?")[1];
          } else {
            urltmp = '/customline/pages/index/index?' + url.split("?")[1];
          }
          wx.navigateTo({
            url: urltmp,
          });
        }
      }
    } catch (err) {

    }

  },
  // 业务图标显示
  getSystemConfig: function () {
    var that = this;
    wx.request({
      url: app.serviceurl + 'GetSystemConfig',
      dataType: 'json',
      success: function (res) {
        if (res.data.isSuccess) {
          app.notice = res.data.Notice;
          var tmp = that.data.summary;

          if (res.data.DingZhi == "1") {
            tmp[0].isenable = true;
            tmp[0].icon = "/pages/image/custome.png";
          } else {
            tmp[0].isenable = false;
            tmp[0].icon = "/pages/image/customeoff.png";
          }

          if (res.data.YueZu == "1") {
            tmp[1].isenable = true;
            tmp[1].icon = "/pages/image/rent.png";
          } else {
            tmp[1].isenable = false;
            tmp[1].icon = "/pages/image/rentoff.png";
          }

          if (res.data.Tourism == "1") {
            tmp[2].isenable = true;
            tmp[2].icon = "/pages/image/play.png";
          } else {
            tmp[2].isenable = false;
            tmp[2].icon = "/pages/image/playoff.png";
          }
          if (res.data.Train == "1") {
            tmp[3].isenable = true;
            tmp[3].icon = "/pages/image/train.png";
          } else {
            tmp[3].isenable = false;
            tmp[3].icon = "/pages/image/trainoff.png";
          }
          that.setData({
            summary: tmp,
            text: res.data.Notice
          });
        }
      },
      fail: function () {}
    })
  },
  // 获取优惠活动
  getActivity: function () {
    try {
      var that = this;
      wx.request({
        url: app.serviceurl + '/CustomLine/CustomQueryDiscount',
        header: {
          Authorization: "Bearer "
        },
        dataType: 'json',
        success: function (res) {
          if (!res.data.Result) {
            return
          }
          var acresult = res.data.Result;
          that.setData({
            acresult: acresult
          })
        },
        fail: function () {}
      })
    } catch (err) {}
  },

  upload: function () {
    var that = this;
    try {
      wx.getStorage({
        key: 'stationname',
        success: function (res) {
          that.setData({
            stationname: res.data,
          });
          app.stationName = res.data;
        },
      });
      wx.getStorage({
        key: 'globalcode',
        success: function (res) {
          app.globalcode = res.data;
        },
      });
      wx.getStorage({
        key: 'target',
        success: function (res) {
          that.setData({
            target: res.data,
          });
          app.target = res.data;
        },
      });
    } catch (err) {}
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    // 第一次获取Token
    if (!app.accesstoken) {
      this.setData({
        ModalSwitch: true
      })
      this.GetUserToken();
    } else {
      this.checkfrom(this.op);
      this.setData({
        ModalSwitch: false
      })
    }
    // 延迟5s执行，没有检测到Token则再次获取
    var t = setTimeout(function () {
      if (!app.accesstoken) {
        that.GetUserToken();
      }
    }, 5000);

    this.upload();
    let isDate = app.startdate;
    if (isDate == null) {
      this.setData({
        date: app.dates()
      })
    } else {
      this.setData({
        date: isDate
      });
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 提示框
  Alert: function (msg) {
    wx.showModal({
      content: msg,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {}
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;

    // if (res.from === 'menu') {
    //   // 来自页面内转发按钮
    //   return app.OnShare();
    // };
    // 2020春节活动分享
    if (!app.accesstoken) {
      return that.Alert("请先点击页面授权")
    }
    return {
      title: "",
      path: `/pages/index/index?user=${app.accesstoken}&dis=true&shareid=${new Date().getTime()}`,
      imageUrl: 'https://img.hn96606.com/images/activity/fenxiang.png',
      success: function (res) {

      },
      fail(err) {
        that.Alert("分享失败")
      }
    }
  },
  // 城际快线
skip:function(){
  wx.navigateToMiniProgram({
    appId: 'wx5c41c321ceb5c552',
    path: 'pages/express/index/index',
    envVersion: 'release',
  })
},
// 城际拼车
carSharing:function(){
  wx.navigateToMiniProgram({
    appId: 'wx5c41c321ceb5c552',
    path: 'pages/carpool/book/book',
    envVersion: 'release',
  })
},
// 跳转到新版小程序
newEdition:function(){
  wx.navigateToMiniProgram({
    appId: 'wx5c41c321ceb5c552',
    path: 'pages/carpool/book/book',
    envVersion: 'release',
  })
},
  // 出发车站
  choosestation: function (e) {
    wx.navigateTo({
      url: '/pages/stations/stations',
    });
  },

  // 目的车站
  choosetarget: function (e) {
    wx.navigateTo({
      url: '/pages/targets/targets',
    });
  },
  // 用户点击活动banner图进入活动详情页面
  disMsgHtml(e) {
    try {
      let index = e.currentTarget.dataset.index;
      let htmlShow = this.webHtmlData.webHtmlShow;
      if (index == 0) {
        if (this.data.disShow) {
          this.setData({
            isTrue: true
          })
          wx.navigateTo({
            url: '/pages/discountMsg/discountMsg',
          });
        }
        if (htmlShow && this.webHtmlData.webHtml1.length > 0) {
          wx.navigateTo({
            url: "/pages/WebHtml/protocol/protocol?index=2",
          });
        }
      }
      if (index == 1 && htmlShow && this.webHtmlData.webHtml2.length > 0) {
        wx.navigateTo({
          url: "/pages/WebHtml/protocol/protocol?index=3",
        });
      }
      if (index == 2 && htmlShow && this.webHtmlData.webHtml3.length > 0) {
        wx.navigateTo({
          url: "/pages/WebHtml/protocol/protocol?index=4",
        });
      }
    } catch (err) {}
  },
  shareMsg() {
    wx.navigateTo({
      url: '/pages/discountMsg/discountMsg',
    });
  },
  submit: function (e) {
    var that = this;
    try {
      wx.requestSubscribeMessage({
        tmplIds: ['x92kQbCz5m_vExtzSBWtG1BDXmu936YilkS9-ZaMbwg'],
        success(res) {},
        complete(data) {
          if (that.data.stationname != '' && that.data.target != '') {
            wx.navigateTo({
              url: '/pages/buslines/buslines'
              // url: '/pages/applySuccess/applySuccess'
              // url:"/pages/personcenter/personcenter"
            });
          } else {
            that.Alert("请选择出发车站和目的地");
          }
        }
      })
    } catch (err) {
      if (that.data.stationname != '' && that.data.target != '') {
        wx.navigateTo({
          url: '/pages/buslines/buslines'
        });
      } else {
        that.Alert("请选择出发车站和目的地");
      }
    }


  },
  // 日期选择
  selectDate: function () {
    wx.navigateTo({
      url: '../calendar/calendar'
    });
  },
  // 相应的业务连接页面跳转
  jump: function (e) {
    // if (this.isYes()) {
    //   return
    // }
    var index = e.currentTarget.dataset.index;
    if (this.data.summary[index].isenable) {
      wx.navigateTo({
        url: this.data.summary[index].url,
      });
    } else {
      wx.showToast({
        title: '尚未开通...',
        icon: 'none',
        duration: 1000
        // image: '../image/location.png'
      })
    }
  }
})